package com.maxsalad.pospal.service;

import com.maxsalad.common.util.JsonUtil;
import com.maxsalad.common.util.OkHttpUtil;
import com.maxsalad.common.util.PropertiesUtil;
import com.maxsalad.pospal.PayMethod;
import com.maxsalad.pospal.entity.order.add.ProductEntity;
import com.maxsalad.pospal.entity.order.add.RequestOrderEntity;
import com.maxsalad.pospal.entity.order.add.ResponseOrder;
import com.maxsalad.uc.dao.OrderDao;
import com.maxsalad.uc.dao.OrderDetailDao;
import com.maxsalad.uc.dto.DOrderDto;
import com.maxsalad.uc.em.OrderStatus;
import com.maxsalad.uc.em.Platform;
import com.maxsalad.uc.entity.ApiParameterEntity;
import com.maxsalad.uc.entity.ApiParameterUtil;
import com.maxsalad.uc.pojo.TOrderDetailEntity;
import com.maxsalad.uc.pojo.TOrderEntity;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.net.util.URLUtil;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2016-03-10.
 */
@Service(value = "pospalOrderService")
public class OrderService extends BaseService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderDetailDao orderDetailDao;

    public ResponseOrder add(long shopId, RequestOrderEntity entity) throws Exception {
        entity.setAppId(getAppId(shopId));

        String requestBody = JsonUtil.serialize(entity);
        Map<String, String> header = getHeader(shopId, requestBody);
        log.debug(requestBody);

        String responseJson = OkHttpUtil.post(getBaseUrl(shopId) + "orderOpenApi/addOnLineOrder", requestBody, header);
        log.debug(responseJson);

        return (ResponseOrder) JsonUtil.deserialize(responseJson, ResponseOrder.class);
    }

    public void upload(int size) {
        ApiParameterUtil.getList().stream().filter(t -> t.getPlatform().toString().equals(Platform.PosPal)).collect(
                () -> new ArrayList<ApiParameterEntity>(),
                (list, item) -> {
                    if (false == list.contains(item)) {
                        list.add(item);
                    }
                },
                (list1, list2) -> {
                    for (ApiParameterEntity item : list2) {
                        if (false == list1.contains(item)) {
                            list1.add(item);
                        }
                    }
                });
        for (ApiParameterEntity item : ApiParameterUtil.getList()) {
            upload(item.getShopId(), size);
        }
    }

    private void upload(long shopId, int size) {
        try {
            List<DOrderDto> list = getOrder(shopId, size);
            for (DOrderDto dto : list) {
                List<ProductEntity> listProduct = new ArrayList<ProductEntity>();
                List<TOrderDetailEntity> listDetail = dto.getDetail();
                if (CollectionUtils.isNotEmpty(listDetail)) {
                    ProductEntity productEntity = null;
                    for (TOrderDetailEntity item : listDetail) {
                        productEntity = new ProductEntity();

                        listProduct.add(productEntity);
                    }
                } else {
                    log.error("明细不存在:" + dto.getDescription() + ":" + dto.getId());
                    continue;
                }


                RequestOrderEntity requestOrderEntity = new RequestOrderEntity();
                requestOrderEntity.setPayMethod(PayMethod.Cash.toString());
                requestOrderEntity.setContactName(dto.getContactName());
                requestOrderEntity.setContactTel(dto.getContactTel());
                requestOrderEntity.setContactAddress(dto.getContactAddress());
                requestOrderEntity.setOrderRemark(dto.getDescription() + ":" + dto.getId());
                requestOrderEntity.setItems(listProduct);

                ResponseOrder responseOrder = add(shopId, requestOrderEntity);
                if ("success".equals(responseOrder.getStatus())) {
                    try {
                        //更新订单状态
                        orderDao.updateNewId(dto.getId(), OrderStatus.Submit.toString(), responseOrder.getData().getOrderNo());
                    } catch (Exception e) {
                        log.error("反更新出错(" + dto.getDescription() + ":" + dto.getId() + ")" + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private List<DOrderDto> getOrder(long shopId, int size) throws Exception {
        List<DOrderDto> listRtn = new ArrayList<DOrderDto>();
        //查询初始状态的订单
        List<TOrderEntity> listOrder = orderDao.queryOrder(shopId, OrderStatus.Init.toString(), size);
        if (CollectionUtils.isNotEmpty(listOrder)) {
            Long[] ids = new Long[listOrder.size()];
            int i = 0;
            for (TOrderEntity orderEntity : listOrder) {
                ids[i] = orderEntity.getId();
                i++;
            }
            List<TOrderDetailEntity> listOrderDetail = orderDetailDao.queryOrderDetailById(ids);

            DOrderDto dto = null;
            for (TOrderEntity orderEntity : listOrder) {
                dto = new DOrderDto();
                BeanUtils.copyProperties(dto, orderEntity);
                List<TOrderDetailEntity> temp = listOrderDetail.stream().filter(t -> t.getOrderId() == orderEntity.getId()).collect(
                        () -> new ArrayList<TOrderDetailEntity>(),
                        (list, item) -> {
                            if (false == list.contains(item)) {
                                list.add(item);
                            }
                        },
                        (list1, list2) -> {
                            for (TOrderDetailEntity item : list2) {
                                if (false == list1.contains(item)) {
                                    list1.add(item);
                                }
                            }
                        });
                dto.setDetail(temp);

                listRtn.add(dto);
            }
        }
        return listRtn;
    }
}
